package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl.salesorder;

import com.alibaba.citrus.cr.common.constant.OrderFeaturesKey;
import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.SalesOrderActivityTypeEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.SalesOrderTypeEnum;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.forecast.functions.forecastorder.constants.ForecastConstants;
import com.alibaba.citrus.cr.forecast.functions.forecastorder.entity.ForecastOrderEntity;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemSearchAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemSearchAbilityDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.ability.NormalPriceQueryUtils;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.service.ForecastOrderBizQueryService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.db.service.CustomSequenceAccessor;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.SearchReqDTO;
import com.epoch.app.bcorder.model.dto.SearchScItemByDBWhenDegradedRequest;
import com.epoch.app.crforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
import com.epoch.app.crforecastsales.dto.request.ConfirmForecastRequest;
import com.epoch.app.crforecastsales.dto.response.ConfirmForecastResponse;
import com.epoch.app.crforecastsales.model.dto.ActivitySDO;
import com.epoch.app.crforecastsales.model.dto.GiftSDO;
import com.epoch.app.crforecastsales.model.dto.QuerySaleUnitRequest;
import com.epoch.app.crforecastsales.model.dto.SelectCombox;
import com.epoch.app.crforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.crpricecenter.model.enums.ActivityTypeEnum;
import com.epoch.app.crpricecenter.model.enums.PriceTypeEnum;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceMainRequest;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceQueryRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderAtomCreateLineRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderBizCreateRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author dongju.fyj
 * @description 订单中心信息补全
 * @date 2024/04/19
 */
@Service
@Order(6)
public class SalesOrderCreateBizAssembleOfOrderCenter implements OrderBizAssemble<SalesOrderBizCreateRequest> {

    private static final Log log = Log.getLogger(SalesOrderCreateBizAssembleOfOrderCenter.class);

    /**
     * 内外码转换方式
     */
    private static String INNER_CODE_TO_OUT_CODE = "inner_code_to_out_code";
    private static String OUT_CODE_TO_INNER_CODE = "out_code_to_inner_code";

    @Resource
    private ForecastOrderBizQueryService forecastOrderBizQueryService;
    @Resource
    private ForecastOrderLineQueryService forecastOrderLineQueryService;
    @Resource
    private NormalPriceQueryUtils normalPriceQueryUtils;
    @Resource
    private ItemQueryAdapter itemQueryAdapter;
    @Resource
    private CustomSequenceAccessor customSequenceAccessor;

    @Override
    public Map<String, Object> query(SalesOrderBizCreateRequest salesOrderBizCreateRequest) {
        return query(Lists.newArrayList(salesOrderBizCreateRequest));
    }

    @Override
    public Map<String, Object> query(List<SalesOrderBizCreateRequest> salesOrderBizCreateRequestList) {
        try {
            if (CollectionUtils.isEmpty(salesOrderBizCreateRequestList)) {
                return Maps.newHashMap();
            }
            List<String> preOrderNos = Lists.newArrayList();
            for (SalesOrderBizCreateRequest createRequest : salesOrderBizCreateRequestList) {
                if (!OrderCategoryEnum.STOCK.getCode().equals(createRequest.getOrderCategoryCode())) {
                    // 目前只有F-B-b订单创建时需要补充活动信息
                    continue;
                }
                if (StringUtils.isNotBlank(createRequest.getPreOrderNo())) {
                    preOrderNos.add(createRequest.getPreOrderNo());
                }
            }
            if (CollectionUtils.isEmpty(preOrderNos)) {
                return Maps.newHashMap();
            }

            // 查询预报订单信息
            List<ForecastOrderSDO> forecastOrderSDOList = forecastOrderBizQueryService.queryByOrderBizNo(preOrderNos);
            Map<String, ForecastOrderSDO> forecastOrderSDOMap = forecastOrderSDOList.stream()
                    .collect(Collectors.toMap(ForecastOrderSDO::getOrderBizId, Function.identity(), (k1, k2) -> k2));

            Map<String, Object> result = Maps.newHashMap();
            result.put(FORECAST_ORDER, forecastOrderSDOMap);
            log.info("SalesOrderCreateBizAssembleOfOrderCenter#query result={}", JSON.toJSONString(result));

            return result;
        } catch (Exception e) {
            log.error("SalesOrderCreateBizAssembleOfOrderCenter#query error", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, SalesOrderBizCreateRequest createRequest) {
        // 预报单
        Map<String, ForecastOrderSDO> forecastOrderSDOMap = getBizInfoMap(queryResponseMap, FORECAST_ORDER, ForecastOrderSDO.class);

        // 校验预报单活动并预占
        Result<String> activityResult = checkActivityAndOccupy(createRequest, forecastOrderSDOMap);
        if (!activityResult.isSuccess()) {
            return activityResult;
        }

        // 其他校验

        return activityResult;
    }

    /**
     * 校验活动并预占
     */
    private Result<String> checkActivityAndOccupy(SalesOrderBizCreateRequest createRequest, Map<String, ForecastOrderSDO> forecastOrderSDOMap) {
        if (MapUtils.isEmpty(forecastOrderSDOMap)) {
            return Result.success(null);
        }
        if (!forecastOrderSDOMap.containsKey(createRequest.getPreOrderNo())) {
            return Result.success(null);
        }
        ForecastOrderSDO forecastOrderSDO = forecastOrderSDOMap.get(createRequest.getPreOrderNo());
        if (CollectionUtils.isEmpty(forecastOrderSDO.getForecastOrderLineSDOList())) {
            return Result.success(null);
        }
        // 根据入参的来源行号过滤预报单明细，只根据选中的明细行进行活动预占
        Set<String> sourceLineNums = createRequest.getOrderDetails()
                .stream().map(SalesOrderAtomCreateLineRequest::getSourceLineNum)
                .collect(Collectors.toSet());
        List<ForecastOrderLineSDO> forecastOrderLineSDOS = forecastOrderSDO.getForecastOrderLineSDOList()
                .stream().filter(line -> sourceLineNums.contains(line.getSerialNumber()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(forecastOrderLineSDOS)) {
            return Result.success(null);
        }
        forecastOrderSDO.setForecastOrderLineSDOList(forecastOrderLineSDOS);
        log.info("SalesOrderCreateBizAssembleOfOrderCenter#assemble forecastOrderSDO={}", JSON.toJSONString(forecastOrderSDO));

        List<Long> forecastLineIds = forecastOrderSDO.getForecastOrderLineSDOList()
                .stream().map(ForecastOrderLineSDO::getId)
                .collect(Collectors.toList());
        try {
            // 生产活动占用序列号，活动释放时会根据序列号进行释放
            String sequenceNo = customSequenceAccessor.getNextStringSequence("cr_forecast_sales", "sequenceNo");
            JSONObject features = StringUtils.isBlank(createRequest.getFeatures())? new JSONObject() : JSON.parseObject(createRequest.getFeatures());
            features.put(OrderFeaturesKey.ACTIVITY_SEQUENCE_NO, sequenceNo);
            // 将预报单明细信息放到入参里，如果后续流程报错了，需要在入口处发送消息释放活动预占
            features.put(OrderFeaturesKey.FORECAST_ORDER_LINE_ID_LIST, forecastLineIds);
            createRequest.setFeatures(features.toJSONString());

            // 占用活动
            ConfirmForecastRequest confirmForecastRequest = new ConfirmForecastRequest();
            confirmForecastRequest.setSequenceNo(sequenceNo);
            JSONObject content = new JSONObject();
            content.put("os", "OrderCenter");
            content.put("codeFlag", OUT_CODE_TO_INNER_CODE);
            confirmForecastRequest.setContent(content.toJSONString());
            log.info("SalesOrderCreateBizAssembleOfOrderCenter#assemble confirmForecastRequest={}", JSON.toJSONString(confirmForecastRequest));

            ForecastOrderEntity forecastOrderEntity = ForecastOrderEntity.of(forecastOrderSDO);
            ConfirmForecastResponse confirmForecastResponse = forecastOrderEntity.confirmCheckForecastNew(confirmForecastRequest, null);
            log.info("SalesOrderCreateBizAssembleOfOrderCenter#assemble confirmForecastResponse={}", JSON.toJSONString(confirmForecastResponse));

            if (MapUtils.isNotEmpty(confirmForecastResponse.getFailOrderLineMap())) {
                String message = confirmForecastResponse.getMessage();
                if (StringUtils.isNotBlank(message)) {
                    message = "活动占用失败:" + message;
                } else {
                    message = "活动占用失败";
                }
                return Result.fail(createRequest.getSourceOrderNo(), "OC-01-001-01-16-024", message);
            }

            // 组装订单活动信息
            log.info("SalesOrderCreateBizAssembleOfOrderCenter#assemble assembleOrderActivityInfo begin createRequest:{}", JSON.toJSONString(createRequest));
            assembleOrderActivityInfo(forecastOrderSDO, createRequest);
            log.info("SalesOrderCreateBizAssembleOfOrderCenter#assemble assembleOrderActivityInfo end createRequest:{}", JSON.toJSONString(createRequest));
        } catch (Exception e) {
            log.error("SalesOrderCreateBizAssembleOfOrderCenter#assemble error", e);
            return Result.fail(createRequest.getSourceOrderNo(), "OC-01-001-01-16-024", "活动占用失败");
        }
        return Result.success(null);
    }

    /**
     * 组装订单活动信息
     */
    private void assembleOrderActivityInfo(ForecastOrderSDO forecastOrderSDO, SalesOrderBizCreateRequest createRequest) {
        Map<String, ForecastOrderLineSDO> forecastOrderLineSDOMap = forecastOrderSDO.getForecastOrderLineSDOList().stream()
                .collect(Collectors.toMap(ForecastOrderLineSDO::getSerialNumber, Function.identity(), (k1, k2) -> k2));

        ListIterator<SalesOrderAtomCreateLineRequest> iterator = createRequest.getOrderDetails().listIterator();
        while (iterator.hasNext()) {
            SalesOrderAtomCreateLineRequest orderLine = iterator.next();
            log.info("SalesOrderCreateBizAssembleOfOrderCenter#assembleOrderActivityInfo orderLine:{}", JSON.toJSONString(orderLine));
            ForecastOrderLineSDO forecastOrderLineSDO = forecastOrderLineSDOMap.get(orderLine.getSourceLineNum());
            if (Objects.isNull(forecastOrderLineSDO)) {
                // 没有对应的预报单信息直接跳过
                continue;
            }
            Map<String, Object> features = forecastOrderLineSDO.getFeatures();
            if (Objects.isNull(features)) {
                // 扩展字段为空直接跳过
                continue;
            }
//            forecastOrderLineSDO.setFrontLineNo(forecastOrderLineSDO.getSerialNumber());

            // 活动类型
            String activityType = "";
            // 活动编码
            String activityCode = "";
            // 活动名称
            String activityName = forecastOrderLineSDO.getActivityName();
            // 活动项目号
            String activityNumber = "";

            if (Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {
                List<ActivitySDO> activitySDOS = JSON.parseArray(JSON.toJSONString(features.get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                // 活动明细不为空
                if (CollectionUtils.isNotEmpty(activitySDOS)) {
                    // 筛选出选中的活动
                    Map<String, ActivitySDO> activitySDOMap = activitySDOS.stream()
                            .filter(ActivitySDO::getIsSelect)
                            .collect(Collectors.toMap(ActivitySDO::getActivityCode, Function.identity(), (v1, v2) -> v1));

                    // 拼接活动类型
                    List<String> activityTypes = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityType).collect(Collectors.toList());
                    activityType = String.join("/", activityTypes);
                    // 拼接活动名称
                    List<String> activityNames = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityName).collect(Collectors.toList());
                    activityName = String.join("/", activityNames);
                    // 拼接活动码
                    List<String> activityCodes = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityCode).collect(Collectors.toList());
                    activityCode = String.join("/", activityCodes);
                    // 拼接活动项目号
                    List<String> activityNumbers = activitySDOS.stream().filter(ActivitySDO::getIsSelect).map(ActivitySDO::getActivityTermid).collect(Collectors.toList());
                    activityNumber = String.join("/", activityNumbers);

                    boolean hitSpecialOfferPrice = false; // 标记是否命中特价活动
                    for (ActivitySDO activitySDO : activitySDOMap.values()) {
                        log.info("SalesOrderCreateBizAssembleOfOrderCenter#assembleOrderActivityInfo activitySDO:{}", JSON.toJSONString(activitySDO));
                        if (Objects.nonNull(activitySDO.getDisableChooseFlag()) && activitySDO.getDisableChooseFlag()) {
                            // 禁止选择的活动直接跳过
                            continue;
                        }
//                        activitySDOMap.put(activitySDO.getActivityCode(), activitySDO);

                        // 特价活动
                        if (SalesOrderActivityTypeEnum.SPECIAL_OFFER_PRICE.getCode().equals(activitySDO.getActivityType())
                                && Objects.nonNull(features.get("activityInventory"))) {
                            int activityInventory = Integer.parseInt(String.valueOf(features.get("activityInventory")));
                            //活动可用余量小于销售数量
                            if (activityInventory < Integer.parseInt(orderLine.getProductQuantity())) {
                                throw new FunctionException("OC-01-001-01-16-047", "活动可用余量小于销售数量");
                            } else {
                                hitSpecialOfferPrice = true;
                                // 活动项目号
//                                activityNumber = activitySDO.getActivityTermid();
                            }

                            // 活动总金额
                            if (Objects.nonNull(forecastOrderLineSDO.getTotalActivityFee())) {
                                orderLine.setActivityTotalAmount(BigDecimal.valueOf(forecastOrderLineSDO.getTotalActivityFee()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                            }
                            // 活动金额
                            if (Objects.nonNull(forecastOrderLineSDO.getActivityPrice())) {
                                orderLine.setActivityPrice(BigDecimal.valueOf(forecastOrderLineSDO.getActivityPrice()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                            }
                        }

                        // 搭赠活动
                        if (SalesOrderActivityTypeEnum.TAKE_GIFT.getCode().equals(activitySDO.getActivityType())) {
                            if (CollectionUtils.isNotEmpty(activitySDO.getChooseGiftList())) {
                                // 活动项目号
//                                activityNumber = activitySDO.getActivityTermid();

                                for (GiftSDO gift : activitySDO.getChooseGiftList()) {
                                    log.info("SalesOrderCreateBizAssembleOfOrderCenter#assembleOrderActivityInfo gift:{}", JSON.toJSONString(gift));

                                    // 补充赠品行的货品信息
                                    SalesOrderAtomCreateLineRequest giftLine = new SalesOrderAtomCreateLineRequest();
                                    giftLine.setSourceLineNum(String.valueOf(Math.abs(orderLine.getSourceLineNum().hashCode())));
                                    giftLine.setProductCode(gift.getScItemCode());
                                    giftLine.setProductName(gift.getGiftName());
                                    giftLine.setProductQuantity(String.valueOf(gift.getGiftNumber()));
                                    giftLine.setSalesUnitCode(gift.getGiftSalesUnitCode());
                                    giftLine.setSalesUnitName(gift.getGiftSalesUnit());
                                    giftLine.setStockUnitCode(gift.getGiftUnitCode());
                                    giftLine.setStockUnitName(gift.getGiftUint());
                                    giftLine.setActivityType(activitySDO.getActivityType());
                                    giftLine.setActivityId(activitySDO.getActivityCode());
                                    giftLine.setActivityLineNo(activitySDO.getActivityTermid());
//                                    giftLine.setActivityPrice(String.valueOf(gift.getGiftPrice() / 100));
                                    giftLine.setGiftFlag("gift");
                                    giftLine.setShippingWarehouseCode(orderLine.getShippingWarehouseCode());
                                    giftLine.setShippingWarehouseName(orderLine.getShippingWarehouseName());
                                    giftLine.setDeliveryFactoryCode(orderLine.getDeliveryFactoryCode());
                                    giftLine.setStockCode(orderLine.getStockCode());
                                    giftLine.setProductionDate(orderLine.getProductionDate());
                                    giftLine.setBuyItemNo(orderLine.getSourceLineNum()); // 赠品行关联主子单

                                    SearchScItemByDBWhenDegradedRequest searchScItemRequest = new SearchScItemByDBWhenDegradedRequest();
                                    SearchReqDTO searchReqDTO = new SearchReqDTO();
                                    searchReqDTO.setScItemIds(Lists.newArrayList(gift.getScItemId()));
                                    searchScItemRequest.setSearchReqDTO(searchReqDTO);

                                    // 补充货品信息
                                    ItemSearchAbilityRequest listRequest = new ItemSearchAbilityRequest();
                                    listRequest.setProductCodes(Lists.newArrayList(giftLine.getProductCode()));
                                    List<ItemSearchAbilityDTO> scItemInfoList = itemQueryAdapter.queryItem(listRequest);
                                    if (CollectionUtils.isNotEmpty(scItemInfoList)) {
                                        ItemSearchAbilityDTO item = scItemInfoList.get(0);
                                        giftLine.setProductBarCode(item.getBarCode());
                                        // 库存单位编码
                                        giftLine.setStockUnitCode(item.getUnitCode());
                                        // 库存单位名称
                                        giftLine.setStockUnitName(item.getUnit());
                                        // 产品编码
                                        giftLine.setInnerProductCode(item.getProductCode());
                                        // 产品名称
                                        giftLine.setInnerProductName(item.getTitle());

                                        // 获取库存单位信息
                                        QuerySaleUnitRequest querySaleUnitRequest = QuerySaleUnitRequest.builder()
                                                .scItemId(item.getScItemId())
                                                .inventoryUnit(giftLine.getStockUnitName())
                                                .inventoryUnitCode(giftLine.getStockUnitCode())
                                                .unitConvert("1")
                                                .build();
                                        Result<List<SelectCombox>> unitListResult = forecastOrderLineQueryService.querySaleUnitList(querySaleUnitRequest);
                                        log.info("SalesOrderCreateBizAssembleOfOrderCenter#assembleOrderActivityInfo unitListResult:{}", JSON.toJSONString(unitListResult));
                                        if (Objects.nonNull(unitListResult) && CollectionUtils.isNotEmpty(unitListResult.getResult())) {
                                            Map<String, SelectCombox> unitMap = unitListResult.getResult().stream().collect(Collectors.toMap(SelectCombox::getValue, Function.identity(), (v1, v2) -> v1));
                                            SelectCombox selected = unitMap.get(giftLine.getSalesUnitCode());
                                            if (selected != null) {
                                                // 库存转换关系
                                                giftLine.setUnitConversionRelationship(selected.getExt());
                                                // 库存数量
                                                giftLine.setStockConversionNum(new BigDecimal(giftLine.getProductQuantity()).divide(new BigDecimal(selected.getExt()), 2, RoundingMode.HALF_UP).toString());
                                            }
                                        }

                                        // 获取价格
                                        Map<String, PolicyPriceQueryRequest> stringPolicyPriceQueryRequestMap = queryGoodsDetailPrice(createRequest, giftLine);
                                        PolicyPriceQueryRequest policyPriceQueryRequest = stringPolicyPriceQueryRequestMap.get(giftLine.getProductCode() + "-" + giftLine.getSalesUnitCode());
                                        log.info("SalesOrderCreateBizAssembleOfOrderCenter#assembleOrderActivityInfo policyPriceQueryRequest:{}", JSON.toJSONString(policyPriceQueryRequest));
                                        if (Objects.isNull(policyPriceQueryRequest) || Objects.isNull(policyPriceQueryRequest.getUnitPrice()) || policyPriceQueryRequest.getUnitPrice() < 0L) {
                                            throw new FunctionException("OC-01-001-01-16-023", "价格格式错误");
                                        }
                                        Long unitPrice = policyPriceQueryRequest.getUnitPrice();
                                        BigDecimal unitPriceNYC = new BigDecimal(String.valueOf(unitPrice)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                                        giftLine.setUnitPrice(unitPriceNYC.toPlainString());

                                        // 计算常规总金额
                                        if (StringUtils.isNotBlank(giftLine.getProductQuantity())) {
                                            Long totalAmount = unitPrice * Long.parseLong(giftLine.getProductQuantity());
                                            BigDecimal totalAmountNYC = new BigDecimal(String.valueOf(totalAmount)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                                            giftLine.setTotalAmount(totalAmountNYC.toPlainString());
                                        }
                                    }
                                    log.info("SalesOrderCreateBizAssembleOfOrderCenter#assembleOrderActivityInfo giftLine:{}", JSON.toJSONString(giftLine));

                                    // 添加赠品行
                                    iterator.add(giftLine);
                                }

                                // 移除特价
                                if (!hitSpecialOfferPrice) {
                                    forecastOrderLineSDO.setActivityPrice(null);
                                    forecastOrderLineSDO.setTotalActivityFee(null);
                                }
                            }
                        }

                        // 补货活动
                        if (Lists.newArrayList(ActivityTypeEnum.REPLENISH_LIST.getValue().split(",")).contains(activitySDO.getActivityType())) {
                            // 活动项目号
                            activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" : String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
                        }
                    }
                }
            }

            // 补货预报订单，且活动明细为空时，从features中取活动项目号
            if (SalesOrderTypeEnum.REPLENISH_ORDER.getCode().equals(createRequest.getSalesOrderType())
                    && StringUtils.isNotEmpty(forecastOrderLineSDO.getActivityCode())
                    && Objects.isNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {
                activityType = SalesOrderActivityTypeEnum.REPLENISHMENT.getCode();
                activityCode = forecastOrderLineSDO.getActivityCode();
                activityName = forecastOrderLineSDO.getActivityName();
                activityNumber = features.get(ForecastConstants.ACTIVITY_NUMBER) == null ? "" : String.valueOf(features.get(ForecastConstants.ACTIVITY_NUMBER));
            }

            if (StringUtils.isNotEmpty(forecastOrderLineSDO.getActivityCode())
                    && Objects.nonNull(features.get(ForecastConstants.ACTIVITY_DETAILS))) {
                List<ActivitySDO> activitySDOList = JSON.parseArray(JSON.toJSONString(features.get(ForecastConstants.ACTIVITY_DETAILS)), ActivitySDO.class);
                List<ActivitySDO> choseActivitySDS = activitySDOList.stream().filter(ActivitySDO::getIsSelect).collect(Collectors.toList());

                // 没有选中的活动时，清空活动信息
                if (CollectionUtils.isEmpty(choseActivitySDS)) {
                    activityType = "";
                    activityCode = "";
                    activityName = "";
                    activityNumber = "";
                }
            }

            // 活动类型
            orderLine.setActivityType(activityType);
            // 活动编码
            orderLine.setActivityId(activityCode);
            // 活动编码
            orderLine.setActivityName(activityName);
            // 活动项目号
            orderLine.setActivityLineNo(activityNumber);
            // 赠品标识设置为非赠品
            orderLine.setGiftFlag("X");
            // 活动对应的预报单明细ID，订单关闭时需要用到
            JSONObject orderLineFeatures;
            if (StringUtils.isNotEmpty(orderLine.getFeatures())) {
                orderLineFeatures = JSON.parseObject(orderLine.getFeatures());
            } else {
                orderLineFeatures = new JSONObject();
            }
            orderLineFeatures.put(OrderFeaturesKey.FORECAST_ORDER_LINE_ID, forecastOrderLineSDO.getId());
            orderLine.setFeatures(orderLineFeatures.toJSONString());
        }
    }

    private Map<String, PolicyPriceQueryRequest> queryGoodsDetailPrice(SalesOrderBizCreateRequest order, SalesOrderAtomCreateLineRequest giftLine) {
        PolicyPriceMainRequest priceMainRequest = convertPriceMainOrder(order, giftLine);

        log.info("SalesOrderBizAssembleOfCostCenter#queryGoodsDetailPrice priceMainRequest: {}", priceMainRequest);
        List<PolicyPriceQueryRequest> policyPriceQueryRequests = normalPriceQueryUtils.queryPolicyPrice(priceMainRequest);
        log.info("SalesOrderBizAssembleOfCostCenter#queryGoodsDetailPrice policyPriceQueryRequests: {}", policyPriceQueryRequests);

        return Optional.ofNullable(policyPriceQueryRequests)
                .orElse(Lists.newArrayList())
                .stream()
                .collect(Collectors.toMap(o -> o.getMaterialCode() + "-" + o.getSalesUnitCode(), p -> p, (v1, v2) -> v1));
    }

    private PolicyPriceMainRequest convertPriceMainOrder(SalesOrderBizCreateRequest order, SalesOrderAtomCreateLineRequest giftLine) {
        log.info("=============convertMainOrder_request:" + JSON.toJSON(order));
        PolicyPriceMainRequest mainOrderInfo = new PolicyPriceMainRequest();
        mainOrderInfo.setFromSys(order.getFromSys());
        mainOrderInfo.setSalesOrganizationCode(order.getSalesOrganizationCode());
        mainOrderInfo.setBusinessType(order.getBusinessType());

        log.info("=============convertMainOrder_mainOrderInfo:" + JSON.toJSON(mainOrderInfo));
        mainOrderInfo.setCalculateItemList(convertPriceOrderLine(giftLine, order));
        return mainOrderInfo;
    }

    private List<PolicyPriceQueryRequest> convertPriceOrderLine(SalesOrderAtomCreateLineRequest giftLine, SalesOrderBizCreateRequest order) {
        if (Objects.isNull(giftLine)) {
            return Lists.newArrayList();
        }
        List<PolicyPriceQueryRequest> responses = Lists.newArrayList();
        PolicyPriceQueryRequest response = PolicyPriceQueryRequest.builder()
                .priceTypeCode(PriceTypeEnum.ZP01.getCode())
                .orgSalesOrganizationCode(order.getSalesOrganizationCode())
                .channelCode(order.getBusinessChannel())
                .scItemGroupCode(order.getProductGroupCode())
                .customerCode(order.getCustomerCode())
                .customerSaleAddressCode(order.getCustomerCode())
                .customerSendAddressCode(order.getShipToPartyCode())
                .salesUnitCode(giftLine.getSalesUnitCode())
                .materialCode(giftLine.getProductCode())
                .departmentCode(order.getSalesDepartmentCode())
                .factoryCode(giftLine.getDeliveryFactoryCode())
                .storePlace(giftLine.getStockCode())
                .build();
        responses.add(response);
        return responses;
    }

}
